const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const log4js = require('./utils/log4j')
const checkToken = require("./utils/checkToken.js");
const cors = require('./utils/cors')
require('./config/db')

const user = require('./routes/user')
const role = require('./routes/role.js')
const menu = require('./routes/menu.js')
const dept = require('./routes/dept.js')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 解决跨域
app.use(cors);

// 验证token
app.use(checkToken);

// routes
app.use(user.routes(), user.allowedMethods())
app.use(role.routes(), role.allowedMethods())
app.use(menu.routes(), menu.allowedMethods())
app.use(dept.routes(), dept.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  // console.error('server error', err, ctx)
  log4js.error(`${err.stack}`)
});

module.exports = app
